﻿using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using NetSurveillance.WebApp.Utilities;

namespace NetSurveillance.WebApp.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
    public class CultureAttribute : FilterAttribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string langStr = filterContext.RouteData.Values["lang"] as string;
            HttpCookie langCookie = filterContext.HttpContext.Request.Cookies["lang"];
            if (string.IsNullOrWhiteSpace(langStr))
            {
                if (langCookie != null)
                {
                    langStr = langCookie.Value;
                }
                else
                {
                    var userLangs = filterContext.HttpContext.Request.UserLanguages;
                    langStr = userLangs != null && userLangs.Length > 0 ? userLangs[0] : PresetValues.DefaultLang;
                }
                filterContext.RouteData.Values["lang"] = langStr;
            }

            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langStr);
            if(langCookie != null && langCookie.Value == langStr) return;
            langCookie = new HttpCookie("lang", langStr) { Expires = DateTime.Now.AddMonths(1) };
            filterContext.HttpContext.Response.SetCookie(langCookie);
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
        }
    }
}